package ku.cat;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import ku.cat.db.DatabaseHelper;
import ku.cat.db.model.AttendanceModel;
import ku.cat.db.model.CourseModel;
import ku.cat.db.model.InstructorModel;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.InputType;
import android.util.Log;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class InstructorActivity extends Activity {

	private static final String TAG = "CAT";

	private static final String COURSE_PREF_NAME = "COURSE_PREF";
	private SharedPreferences COURSE_PREF;
	private SharedPreferences.Editor COURSE_PREF_EDITOR;

	Preview preview;

	TextView instructorNameTextView;

	Button takePic;

	InstructorModel instructor;

	String picFileName;

	DatabaseHelper db;
	CourseModel[] course;
	CourseModel course_selected;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.instructorform);

		// course
		COURSE_PREF = getSharedPreferences(COURSE_PREF_NAME, 0);
		COURSE_PREF_EDITOR = COURSE_PREF.edit();

		// FIXME TODO get course from DB
		db = new DatabaseHelper(getApplicationContext());

		Spinner sp_course = (Spinner) findViewById(R.id.pro_course);
		// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
		// this, R.array.planets_array,
		// android.R.layout.simple_spinner_item);
		// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// sp_course.setAdapter(adapter);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				getApplicationContext(), android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_course.setAdapter(adapter);

		course = db.getCourseAll();

		if (course.length > 0) {
			for (int i = 0; i < course.length; i++) {
				adapter.add(course[i].getCourse_name_en());
			}
		}

		sp_course.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {

				course_selected = course[pos];

				COURSE_PREF_EDITOR.putString("course_id",
						course[pos].getCourse_id());
				COURSE_PREF_EDITOR.putString("course_name_th",
						course[pos].getCourse_name_th());
				COURSE_PREF_EDITOR.putString("course_name_en",
						course[pos].getCourse_name_en());
				COURSE_PREF_EDITOR.putString("credit", course[pos].getCredit());
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		// time
		// FIXME format time
		TextView time = (TextView) findViewById(R.id.tv_time);
		time.setText(new Date().toLocaleString());

		// camera
		preview = new Preview(getApplicationContext());
		((FrameLayout) findViewById(R.id.instr_preview)).addView(preview);

		takePic = (Button) findViewById(R.id.buttonClick);
		takePic.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				takePhoto();

				// TODO FIXME set data and insert database
				if (instructor != null) {
					if (course_selected != null) {
						AttendanceModel att = new AttendanceModel();
						att.setStudentrfid(instructor.getRfid());
						att.setClassid(course_selected.getCourse_id());
						att.setFilename(picFileName);
						att.setReady(true);
						att.setUpload(false);
						att.setStamptime(new Date());

						db.addAttendance(att);

						startActivity(new Intent(getApplicationContext(),
								ClassAttendantActivity.class));
					} else {
						AlertDialog.Builder alertError = new AlertDialog.Builder(
								getApplicationContext());

						alertError.setTitle("ผิดพลาด");
						alertError.setMessage("กรุณาเลือกวิชาที่สอน");

						alertError.show();
					}

				} else {
					AlertDialog.Builder alertError = new AlertDialog.Builder(
							getApplicationContext());

					alertError.setTitle("ผิดพลาด");
					alertError.setMessage("กรุณากรอกรหัสผู้สอน");

					alertError.show();
				}

			}
		});

	}

	// manual key(forget card)
	public void manKey(View view) {
		Log.d(TAG, "manKey");

		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("กรอกข้อมูล");
		alert.setMessage("กรอกรหัสอาจารย์");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		input.setInputType(InputType.TYPE_CLASS_NUMBER);
		alert.setView(input);

		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// get data from alertBox
				Editable value = input.getText();

				// TODO find Instructor code and map data

				instructor = db.getInstructorFromRFIDCode(value.toString());

				if (instructor != null) {
					// set view
					instructorNameTextView = (TextView) findViewById(R.id.instr_name);
					instructorNameTextView.setText(instructor.getFirstName()
							+ " " + instructor.getLastName());
				} else {
					AlertDialog.Builder alertError = new AlertDialog.Builder(
							getApplicationContext());

					alertError.setTitle("ผิดพลาด");
					alertError.setMessage("ไม่พบรหัส  " + value);

					alertError.show();
				}

				// FIXME to test fix name and course
				// instrName = (TextView) findViewById(R.id.instr_name);
				// instrName
				// .setText("à¸­à¸²à¸ˆà¸²à¸£à¸¢à¹Œà¸—à¸”à¸ªà¸­à¸š à¸•à¸±à¹‰à¸‡à¸Šà¸·à¹ˆà¸­");
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();

	}

	// take a photo
	public void takePhoto() {
		preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
			Log.e(TAG, e.getMessage());
		}

		preview.camera.startPreview();

		// release camera
		if (preview.camera != null) {
			preview.camera.stopPreview();
			preview.camera.release();
			preview.camera = null;
		}

	}

	ShutterCallback shutterCallback = new ShutterCallback() {
		public void onShutter() {
			Log.d(TAG, "onShutter'd");
		}
	};

	/** Handles data for raw picture */
	PictureCallback rawCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			Log.d(TAG, "onPictureTaken - raw");
		}
	};

	/** Handles data for jpeg picture */
	PictureCallback jpegCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			FileOutputStream outStream = null;
			try {
				// write to local sandbox file system
				// outStream =
				// CameraDemo.this.openFileOutput(String.format("%d.jpg",
				// System.currentTimeMillis()), 0);

				// write to sdcard with timestamp in pattern yyyyMMdd_HHmmss.jpg
				Log.d(TAG, Environment.getExternalStorageDirectory().toString());

				picFileName = String.format(Environment
						.getExternalStorageDirectory().toString() + "/%s.jpg",
						new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
								.format(new Date()));

				outStream = new FileOutputStream(picFileName);
				outStream.write(data);
				outStream.flush();
				outStream.close();
				Log.d(TAG, "onPictureTaken - : " + data.length);
			} catch (FileNotFoundException e) {
				// e.printStackTrace();
				Log.d(TAG, e.getMessage());
			} catch (IOException e) {
				// e.printStackTrace();
				Log.d(TAG, e.getMessage());
			} finally {
			}
			Log.d(TAG, "onPictureTaken - jpeg");
		}
	};

	// menu
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.instrutor_menu, menu);
		return true;
	};

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.instr_exit:
			finish();
			break;
		case R.id.instr_student:

			// release camera
			if (preview.camera != null) {
				preview.camera.stopPreview();
				preview.camera.release();
				preview.camera = null;
			}

			startActivity(new Intent(this, ClassAttendantActivity.class));

			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}
